package com.zheng.hospital.controller;

import com.zheng.hospital.common.result.CommonResult;
import com.zheng.hospital.service.OrderService;
import com.zheng.hospital.service.PaymentService;
import com.zheng.hospital.service.WxPayService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/api/order/weixin")
public class WxPayController {
    @Autowired
    WxPayService wxPayService;
    @Autowired
    PaymentService paymentService;

    /**
     * 生成微信支付二维码
     * @param orderId
     * @return
     */
    @ApiOperation("生成微信支付二维码")
    @GetMapping("/createNative/{orderId}")
    public CommonResult createNative(@PathVariable Long orderId) {
        Map code = wxPayService.createNative(orderId);
        return CommonResult.ok(code);
    }

    /**
     * 查询支付状态
     * @param orderId
     * @return
     */
    @ApiOperation(value = "查询支付状态")
    @GetMapping("queryPayStatus/{orderId}")
    public CommonResult queryPayStatus(@PathVariable Long orderId) {
        //调用微信接口实现支付状态查询
        Map<String,String> resultMap = wxPayService.queryPayStatus(orderId);
        //判断
        if(resultMap == null) {
            return CommonResult.fail().message("支付出错");
        }
        if("SUCCESS".equals(resultMap.get("trade_state"))) { //支付成功
            //更新订单状态
            String out_trade_no = resultMap.get("out_trade_no");//订单编码
            paymentService.paySuccess(out_trade_no,resultMap);
            return CommonResult.ok().message("支付成功");
        }
        return CommonResult.ok().message("支付中");
    }
}
